<script>
import echarts from 'echarts'

export default {
  props: {
    data: {
      type: Object,
      default: () => {
        return {}
      },
    },
    title: {
      type: String,
      default: '',
    },
    type: {
      type: String,
      default: 'bar',
    },
    height: {
      type: String,
      default: '200px',
    },
  },
  data() {
    return {
      echarts: null,
    }
  },
  watch: {
    data: {
      handler() {
        if (this.data.xArr) {
          this.$nextTick(() => {
            this.draw()
            window.addEventListener('resize', () => {
              this.echarts && this.echarts.resize()
            })
          })
        }
      },
      immediate: true,
    },
  },
  methods: {
    draw() {
      this.echarts = echarts.init(this.$refs.charts)
      this.echarts.setOption(
        {
          grid: {
            top: '5%',
            left: '1%',
            bottom: '3%',
            right: '3%',
            containLabel: true,
          },
          color: ['#FF6600', '#FF6C00', '#52FFC8', '#C8C8C8'],
          tooltip: {
            trigger: 'axis',
          },
          xAxis: {
            type: 'category',
            data: this.data.xArr,
            axisLabel: {
              interval: 1,
            },
            axisLine: {
              lineStyle: {
                color: '#EB7424', // 颜色
              },
            },
          },
          yAxis: {
            show: true,
            type: 'value',
            axisLine: { show: false },
            axisTick: { show: false },
            splitLine: { show: false },
            axisLabel: {
              formatter: '{value}',
              textStyle: {
                color: '#EB7424',
              },
            },
          },
          series: [
            {
              name: '',
              type: 'line',
              data: this.data.yArr,
              symbol: 'circle', //折线点设置为实心点
              symbolSize: 6, //折线点的大小
              areaStyle: {
                normal: {
                  barBorderRadius: 25,
                  color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                    { offset: 0, color: 'rgba(255, 102, 0, 1)' },
                    { offset: 1, color: 'rgba(255, 208, 80, 0.4)' },
                  ]),
                },
              },
            },
          ],
        },
        true
      )
      this.echarts.on('click', (params) => {
        console.log(params)
      })
    },
    cutOut(str, num = 8) {
      if (str.length > num) {
        str = str.substring(0, num) + '...'
      }
      return str
    },
  },
}
</script>

<template lang="pug">
.echarts
  .draw(ref='charts', :style='{ height: height }')
</template>

<style lang="stylus" scoped></style>
